package com.qumitech.visualnovel.service.voiceRoom.impl;

import com.alibaba.fastjson.JSONObject;
import com.qumitech.visualnovel.component.annotation.RequireWhiteList;
import com.qumitech.visualnovel.component.exception.BusinessException;
import com.qumitech.visualnovel.component.util.HttpInvokeUtil;
import com.qumitech.visualnovel.component.util.TimeUtils;
import com.qumitech.visualnovel.model.common.BaseRsp;
import com.qumitech.visualnovel.model.common.ResultEnum;
import com.qumitech.visualnovel.controller.vo.player.UserResetRecordVO;
import com.qumitech.visualnovel.controller.vo.player.UserResetVO;
import com.qumitech.visualnovel.datasource.console.VoiceRoomProfitDOMapper;
import com.qumitech.visualnovel.datasource.console.VoiceRoomPropertyChangeDOMapper;
import com.qumitech.visualnovel.datasource.console.VoiceRoomSupplementRecordDOMapper;
import com.qumitech.visualnovel.model.dao.console.UserInfo;
import com.qumitech.visualnovel.model.dao.console.VoiceRoomProfitDO;
import com.qumitech.visualnovel.model.dao.console.VoiceRoomPropertyChangeDO;
import com.qumitech.visualnovel.model.dao.console.VoiceRoomSupplementRecordDO;
import com.qumitech.visualnovel.model.common.UrlConstant;
import com.qumitech.visualnovel.pubdef.dto.voiceroom.*;
import com.qumitech.visualnovel.pubdef.dto.voiceroom.query.VoiceRoomAdminQueryDTO;
import com.qumitech.visualnovel.pubdef.dto.voiceroom.query.VoiceRoomProfitQueryDTO;
import com.qumitech.visualnovel.pubdef.dto.voiceroom.query.VoiceRoomPropertyChangeQueryDTO;
import com.qumitech.visualnovel.pubdef.dto.voiceroom.query.VoiceRoomSupplementQueryDTO;
import com.qumitech.visualnovel.service.voiceRoom.VoiceRoomManageService;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.beanutils.BeanMap;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class VoiceRoomManageServiceImpl implements VoiceRoomManageService {

    private final String VOICE_ROOM_CONSOLE_URL = "/voiceroom/console";

    private final String VOICE_ROOM_REBATE_URL = "/voiceroom/console/rebate";

    private final String VOICE_ROOM_REBATE_WITHDRAW_URL = "/voiceroom/console/rebate/withdraw";

    private final String VOICE_ROOM_REBATE_SUPPLEMENT_URL = "/voiceroom/console/rebate/supplement";

    private final String VOICE_ROOM_REBATE_CONFIG_URL = "/voiceroom/console/rebate/config";


    private final String VOICE_ROOM_DEFAULT_CONFIG_URL = "/voiceroom/console/config";


    private final String VOICE_ROOM_REBATE_BILL_URL = "/voiceroom/console/rebate/bill";

    private final String VOICE_ROOM_GET_RESET = "/admin/usercontent/voice_room/%s/reset";
    private final String VOICE_ROOM_PUT_RESET = "/admin/usercontent/voice_room/%s/reset";
    private final String VOICE_ROOM_GET_RESET_RECORD  = "/admin/usercontent/voice_room/reset_record";


    @Autowired
    VoiceRoomSupplementRecordDOMapper voiceRoomSupplementRecordDOMapper;

    @Autowired
    VoiceRoomProfitDOMapper voiceRoomProfitDOMapper;

    @Autowired
    VoiceRoomPropertyChangeDOMapper voiceRoomPropertyChangeDOMapper;

    @RequireWhiteList
    @GetMapping("")
    public BaseRsp listVoiceRoom(VoiceRoomAdminQueryDTO queryDTO) {
        String url = UrlConstant.SERVER_URL + VOICE_ROOM_CONSOLE_URL;
        JSONObject o = JSONObject.parseObject(JSONObject.toJSONString(queryDTO));
        Map<String, Object> req = JSONObject.toJavaObject(o, Map.class);
        String body = HttpInvokeUtil.httpGet(url, req);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp updateVoiceRoom(VoiceRoomAdminUpdateDTO updateDTO) {
        updateDTO.setOperator(getActiveUserName());

        String url = UrlConstant.SERVER_URL + VOICE_ROOM_CONSOLE_URL;
        String req = JSONObject.toJSONString(updateDTO);
        String body = HttpInvokeUtil.httpPutJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);

        if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()) {
            return rsp;
        }

        VoiceRoomPropertyChangeDO propertyChangeDO = new VoiceRoomPropertyChangeDO();
        BeanUtils.copyProperties(updateDTO, propertyChangeDO);

        propertyChangeDO.setOperatePerson(updateDTO.getOperator());
        if (updateDTO.getRebateType() != null){
            propertyChangeDO.setRebateType(Integer.valueOf(updateDTO.getRebateType()));
            voiceRoomPropertyChangeDOMapper.insertSelective(propertyChangeDO);
        }
        return rsp;

    }

    @Override
    public List<VoiceRoomPropertyChangeDO> listVoiceRoomPropertyChange(VoiceRoomPropertyChangeQueryDTO queryDTO) {
        return voiceRoomPropertyChangeDOMapper.getList(queryDTO);
    }

    @Override
    public Integer countVoiceRoomPropertyChange(VoiceRoomPropertyChangeQueryDTO queryDTO) {
        return voiceRoomPropertyChangeDOMapper.getCount(queryDTO);
    }

    @Override
    public VoiceRoomProfitStatistic getVoiceRoomProfitStatistic(String roomId) {
        VoiceRoomProfitStatistic voiceRoomProfitStatistic = new VoiceRoomProfitStatistic();
        VoiceRoomProfitDO lastWeekData = voiceRoomProfitDOMapper.getVoiceRoomProfitStatistic(roomId,
                TimeUtils.formatDate(TimeUtils.getBeginDayOfLastWeek()), TimeUtils.formatDate(TimeUtils.getEndDayOfLastWeek()));
        VoiceRoomProfitDO currentWeekData = voiceRoomProfitDOMapper.getVoiceRoomProfitStatistic(roomId,
                TimeUtils.formatDate(TimeUtils.getBeginDayOfWeek()), TimeUtils.formatDate(TimeUtils.getEndDayOfWeek()));
        voiceRoomProfitStatistic.setRoomId(roomId);
        voiceRoomProfitStatistic.setLastWeekGiftProfit(lastWeekData.getGiftProfit());
        voiceRoomProfitStatistic.setLastWeekMagicBoxProfit(lastWeekData.getMagicBoxProfit());
        voiceRoomProfitStatistic.setLastWeekPoundEggProfit(lastWeekData.getPoundEggProfit());
        voiceRoomProfitStatistic.setLastWeekProfit(lastWeekData.getGiftProfit() + lastWeekData.getMagicBoxProfit() + lastWeekData.getPoundEggProfit());
        voiceRoomProfitStatistic.setCurrentWeekGiftProfit(currentWeekData.getGiftProfit());
        voiceRoomProfitStatistic.setCurrentWeekMagicBoxProfit(currentWeekData.getMagicBoxProfit());
        voiceRoomProfitStatistic.setCurrentWeekPoundEggProfit(currentWeekData.getPoundEggProfit());
        voiceRoomProfitStatistic.setCurrentWeekProfit(currentWeekData.getGiftProfit() + currentWeekData.getMagicBoxProfit() + currentWeekData.getPoundEggProfit());
        return voiceRoomProfitStatistic;
    }

    @Override
    public List<VoiceRoomProfitDO> listVoiceRoomProfit(VoiceRoomProfitQueryDTO queryDTO) {
        return voiceRoomProfitDOMapper.getList(queryDTO);
    }

    @Override
    public Integer countVoiceRoomProfit(VoiceRoomProfitQueryDTO queryDTO) {
        return voiceRoomProfitDOMapper.getCount(queryDTO);
    }

    @Override
    public BaseRsp listVoiceRoomRebateWithdraw(RebateWithdrawQueryDTO queryDTO) {
        String url = UrlConstant.SERVER_URL + VOICE_ROOM_REBATE_WITHDRAW_URL;
        JSONObject o = JSONObject.parseObject(JSONObject.toJSONString(queryDTO));
        Map<String, Object> req = JSONObject.toJavaObject(o, Map.class);
        String body = HttpInvokeUtil.httpGet(url, req);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp verifyVoiceRoomRebateWithdraw(RebateWithdrawUpdateDTO updateDTO) {
        String url = UrlConstant.SERVER_URL + VOICE_ROOM_REBATE_WITHDRAW_URL + "/" + updateDTO.getId();
        updateDTO.setOperator(getActiveUserName());
        String req = JSONObject.toJSONString(updateDTO);
        String body = HttpInvokeUtil.httpPutJson(url, req, UrlConstant.DefaultEncode, null);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp updateVoiceRoomRebateSupplement(RebateAddDTO addDTO) {
        VoiceRoomSupplementRecordDO supplementRecordDO = new VoiceRoomSupplementRecordDO();
        if (addDTO.getWeek() == 1) {
            String weekStr = String.format("当前周(%s-%s)", TimeUtils.formatDate(TimeUtils.getBeginDayOfWeek()),
                    TimeUtils.formatDate(TimeUtils.getEndDayOfWeek()));
            supplementRecordDO.setWeek(weekStr);
        } else if (addDTO.getWeek() == 2) {
            String weekStr = String.format("上周(%s-%s)", TimeUtils.formatDate(TimeUtils.getBeginDayOfLastWeek()),
                    TimeUtils.formatDate(TimeUtils.getEndDayOfLastWeek()));
            supplementRecordDO.setWeek(weekStr);
        }
        supplementRecordDO.setStatus((byte) 1);
        supplementRecordDO.setRoomId(addDTO.getRoomId());
        supplementRecordDO.setRoomName(addDTO.getRoomName());
        supplementRecordDO.setOperatePerson(getActiveUserName());
        supplementRecordDO.setValue(String.valueOf(addDTO.getValue()));

        String url = UrlConstant.SERVER_URL + VOICE_ROOM_REBATE_SUPPLEMENT_URL + "/" + addDTO.getRoomId();
        String req = JSONObject.toJSONString(addDTO);
        String body = HttpInvokeUtil.httpPutJson(url, req, UrlConstant.DefaultEncode, null);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);


        if (rsp == null || rsp.getStatus() != ResultEnum.SUCCESS.getState()) {
            supplementRecordDO.setStatus((byte) 2);
            voiceRoomSupplementRecordDOMapper.insertSelective(supplementRecordDO);
            return rsp;
        }
        voiceRoomSupplementRecordDOMapper.insertSelective(supplementRecordDO);
        return rsp;
    }

    @Override
    public List<VoiceRoomRebateSupplementDTO> listVoiceRoomRebateSupplement(VoiceRoomSupplementQueryDTO queryDTO) {
        return voiceRoomSupplementRecordDOMapper.getList(queryDTO);
    }

    @Override
    public Integer countVoiceRoomRebateSupplement(VoiceRoomSupplementQueryDTO queryDTO) {
        return voiceRoomSupplementRecordDOMapper.getCount(queryDTO);
    }

    @Override
    public BaseRsp listRebateConfig(String roomId) {
        String url = UrlConstant.SERVER_URL + VOICE_ROOM_REBATE_CONFIG_URL + "/" + roomId;
        Map<String, Object> req = new HashMap<>();
        String body = HttpInvokeUtil.httpGet(url, req);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp updateVoiceRoomRebate(VoiceRoomRebateUpdateDTO updateDTO) {
        String url = UrlConstant.SERVER_URL + VOICE_ROOM_REBATE_URL + "/" + updateDTO.getRoomId();
        String req = JSONObject.toJSONString(updateDTO);
        String body = HttpInvokeUtil.httpPutJson(url, req, UrlConstant.DefaultEncode, null);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp listDefaultConfig() {
        String url = UrlConstant.SERVER_URL + VOICE_ROOM_DEFAULT_CONFIG_URL;
        JSONObject o = new JSONObject();
        Map<String, Object> req = JSONObject.toJavaObject(o, Map.class);
        String body = HttpInvokeUtil.httpGet(url, req);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        return rsp;
    }

    @Override
    public BaseRsp updateDefaultConfig(VoiceRoomDefaultConfigDTO updateConfigDTO) {
        String url = UrlConstant.SERVER_URL + VOICE_ROOM_DEFAULT_CONFIG_URL;
        String req = JSONObject.toJSONString(updateConfigDTO);
        String body = HttpInvokeUtil.httpPutJson(url, req, UrlConstant.DefaultEncode, null);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp deleteDefaultConfig(long defaultConfigId) {
        String url = UrlConstant.SERVER_URL + VOICE_ROOM_DEFAULT_CONFIG_URL + "/" + defaultConfigId;
        Map<String, String> headMap = new HashMap<>();
        String body = HttpInvokeUtil.httpDelete(url, headMap);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp addDefaultConfig(VoiceRoomDefaultConfigDTO addConfigDTO) {
        String url = UrlConstant.SERVER_URL + VOICE_ROOM_DEFAULT_CONFIG_URL;
        String req = JSONObject.toJSONString(addConfigDTO);
        String body = HttpInvokeUtil.httpPostJson(url, req, UrlConstant.DefaultEncode, null);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp getVoiceRoomType() {
        String url = UrlConstant.SERVER_URL + VOICE_ROOM_CONSOLE_URL + "/room_type";
        JSONObject o = new JSONObject();
        Map<String, Object> req = JSONObject.toJavaObject(o, Map.class);
        String body = HttpInvokeUtil.httpGet(url, req);
        BaseRsp rsp = JSONObject.parseObject(body, BaseRsp.class);
        return rsp;
    }

    @Override
    public BaseRsp getVoiceRoomRebateBill(VoiceRoomRebateBillAdminQueryDTO queryDTO) {
        String url = UrlConstant.SERVER_URL + VOICE_ROOM_REBATE_BILL_URL;
        JSONObject o = JSONObject.parseObject(JSONObject.toJSONString(queryDTO));
        Map<String, Object> req = JSONObject.toJavaObject(o, Map.class);
        String body = HttpInvokeUtil.httpGet(url, req);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp changeVoiceRoomRebate(VoiceRoomRebateAdminDTO roomRebateAdminDTO) {
        String url = UrlConstant.SERVER_URL + VOICE_ROOM_CONSOLE_URL + "/" + roomRebateAdminDTO.getRoomId() + "/rebate/change";
        roomRebateAdminDTO.setOperator(getActiveUserName());
        String req = JSONObject.toJSONString(roomRebateAdminDTO);
        String body = HttpInvokeUtil.httpPutJson(url, req, UrlConstant.DefaultEncode, null);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp getVoiceRoomReset(String roomId) {
        String url = UrlConstant.SERVER_URL + String.format(VOICE_ROOM_GET_RESET, roomId);
        String body = HttpInvokeUtil.httpGet(url, new HashMap<>());
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp resetVoiceRoom(UserResetVO userResetVO) {
        Subject subject = SecurityUtils.getSubject();
        UserInfo activeUser = (UserInfo) subject.getPrincipal();
        userResetVO.setOperatorId(activeUser.getUid().longValue());
        userResetVO.setOperator(activeUser.getUsername());
        String url = UrlConstant.SERVER_URL + String.format(VOICE_ROOM_PUT_RESET, userResetVO.getRoomId());
        String req = JSONObject.toJSONString(userResetVO);
        String body = HttpInvokeUtil.httpPutJson(url,req,UrlConstant.DefaultEncode,null);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    @Override
    public BaseRsp getVoiceRoomResetRecords(UserResetRecordVO resetRecordVO) {
        String url = UrlConstant.SERVER_URL + VOICE_ROOM_GET_RESET_RECORD;
        String body = HttpInvokeUtil.httpGetT(url, resetRecordVO);
        return JSONObject.parseObject(body, BaseRsp.class);
    }

    private String getActiveUserName() {
        Subject subject = SecurityUtils.getSubject();
        UserInfo activeUser = (UserInfo) subject.getPrincipal();
        return activeUser.getUsername();
    }


}
